<?php
namespace cms\modules\v1\models\userReceipt;

use cms\modules\v1\models\admin\Admin;
use common\models\Functions;
use common\models\Status;
use common\models\user\User;
use yii\base\Exception;
use Yii;
/**
 * Class EmployeeInfo
 * @package api\modules\v1\models\employee
 */
class ReceiptBank extends \common\models\userReceipt\ReceiptBank
{
    public function getInfo($id = 0) {
        try {
            $admin = (new Admin())->checkLogin();

            if (empty($id)) {
                throw new Exception("参数错误");
            }

            $info = static::getOneByWhere(['user_id' => $id]);

            $data = [
                "card_no" => '',
                "bank_name" => '',
                "bank_holder" => ''
            ];

            if (!empty($info)) {
                $data['card_no'] = $info['card_no'];
                $data['bank_name'] = $info['bank_name'];
                $data['bank_holder'] = $info['bank_holder'];
            }

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function saveInfo() {
        try {
            $admin = (new Admin())->checkLogin();

            $post = \Yii::$app->request->post();

            $cardNo = $post['card_no'];
            $bankName = $post['bank_name'];
            $bankHolder = $post['bank_holder'];

            $id = (int) $post['id'];
            if (empty($id)) {
                throw new Exception("参数错误");
            }

            if (empty($cardNo) || empty($bankName) || empty($bankHolder)) {
                throw new Exception("请完善信息");
            }

//            // 检查是否被绑定
//            $info = static::getOneByWhere(['card_no' => $cardNo]);
//            if (!empty($info) && $info['user_id'] != $id) {
//                throw new Exception("该银行卡已被绑定，请更换其他银行卡");
//            }

            $data['card_no'] = $cardNo;
            $data['bank_name'] = $bankName;
            $data['bank_holder'] = $bankHolder;

            $checkInfo = static::getOneByWhere(['user_id' => $id]);

            if (empty($checkInfo)) {
                $data['create_time'] = date("Y-m-d H:i:s");
                $data['user_id'] = $id;
                $res = static::insertDataWithLog($data);
            } else {
                $data['update_time'] = date("Y-m-d H:i:s");
                $res = static::updateDataWithLog($data, ['id' => $checkInfo['id']]);
            }

            return Functions::formatRestAPI(0, '保存成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {
            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'create_time DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @param $search
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
        $get = Yii::$app->request->get();
        if (!empty($get['status'])) {
            $where['status'] = (int) $get['status'];
        }
        if (!empty($get['card_no'])) {
            $andWhere[] = ["LIKE", "card_no", $get['card_no']];
        }

        if (!empty($get['phone'])) {
            $userInfo = User::getOneByWhere(['login_name' => $get['phone']], "id");
            $where["user_id"] = $userInfo['id'];
        }


        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }
        $list = $query->with(["user"])->asArray()->all();
        foreach ($list as &$v) {
            $v['card_photo'] = static::getImages($v['card_photo']);
        }
        return $list;
    }
    public function audit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            $post = Yii::$app->request->post();
            $id = (int) $post["id"];

            if (empty($id)) {
                throw new Exception("参数错误");
            }

            $status = (int) $post["status"];
            if (empty($status)) {
                throw new Exception("请选择审核结果");
            }

            if ($status == Status::AUDIT_RECEIPT_STATUS_SUCCESS) {
                $this->auditSuccess($id);
            }

            if ($status == Status::AUDIT_RECEIPT_STATUS_FAILED) {
                $this->auditFailed($id, $post['reason']);
            }

            # 此条改成待修改
            if ($status == Status::AUDIT_RECEIPT_STATUS_MODIFY) {
                $db['status'] = Status::AUDIT_RECEIPT_STATUS_MODIFY;
                $res = static::updateData($db, ['id' => $id]);
                if ($res < 1) {
                    throw new Exception('该信息已被操作');
                }
            }
            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function auditSuccess($id = 0) {

        $info = static::getOneInfoById($id);
        if ($info['status'] != Status::AUDIT_RECEIPT_STATUS_AUDIT) {
//            throw new Exception('该信息未在审核中');
        }
        # 检查活动
        (new UserActiveLog())->checkAndRecord($info['user_id']);
        # 此条改成过审
        $db['status'] = Status::AUDIT_RECEIPT_STATUS_SUCCESS;
        $db['reason'] = "";
        $res = static::updateData($db, ['id' => $id]);
        if ($res < 1) {
            throw new Exception('该信息已被操作');
        }


    }

    public function auditFailed($id = 0, $reason = '') {
        $info = static::getOneInfoById($id);

        if ($info['status'] != Status::AUDIT_RECEIPT_STATUS_AUDIT) {
//            throw new Exception('该信息未在审核中');
        }

        $db['status'] = Status::AUDIT_RECEIPT_STATUS_FAILED;
        $res = static::updateData($db, ['id' => $id]);
        if ($res < 1) {
            throw new Exception('该订单已被操作');
        }

        $db['reason'] = $reason;
        $res = static::updateData($db, ['id' => $id]);
        if ($res < 1) {
            throw new Exception('该订单已被操作');
        }

        # 执行封停
        $userDB['status'] = Status::COMMON_RADIO_NO;
        User::updateData($userDB, ['id' => $info['user_id']]);
    }
}
